#!/bin/bash
# 依赖：tree jq
set -e
function print_definition {
cat << EOF
{
    "type": "function",
    "function": {
        "name": "dir_tree",
        "description": "获取目录的文件夹树",
        "parameters": {
            "type": "object",
            "properties":{
                "path":{
                    "type":"string",
                    "description": "目标目录"
                },
                "max_depth":{
                    "type":"number",
                    "description":"最大深度"
                }
            }
        }
    }
}

EOF
exit
}
function print_system {
cat << EOF
### dir_tree 工具
- 在\`path\`路径下执行\`tree <path> -a -L <max_depth>\`命令
- 默认打印当前目录
- 先获取当前路径下的文件信息再开始完成用户请求
- 目录、文件等系统资源可能在对话中变动，有时需要反复确认之前获取的系统资源

#### 当前目录结构（注意 depth = 1）
`tree -a -L1`

EOF
exit
}
if [ $# -gt 0 ]; then
    if [ "$1" = '--help' ]; then
        print_system
    elif [ "$1" = '-h' ]; then
        print_system
    elif [ "$1" = '--usage' ]; then
        print_definition
    elif [ "$1" = '-?' ]; then
        print_definition
    fi
fi
if [ $# -eq 0 ]; then
    exit 1
fi
set +e
path=$(echo "$1" | jq -re '.path')
if [ $? -ne 0 ]; then
    path='.'
fi
max_depth=$(echo "$1" | jq -re '.max_depth')
if [ $? -eq 0 ]; then
    set -e
    tree "$path" -a "-L$max_depth" 1>&2
else
    set -e
    tree "$path" -a 1>&2
fi